/**
 * @author SilverBiology, LLC
 * @website http://code.google.com/p/gbif-spreadsheet-processor/
*/
Ext.namespace('GBIF');
Ext.namespace('GBIF.GeoSpatial')

GBIF.GeoSpatial.GeoSpatialPortal = function(config){

	config = config || {}
	
	var items = [];

	if (config.showLayer) {
		this.container = new GBIF.GeoSpatial.Container({
				region: 'west'
			,	split: true
			,	minWidth: 225
			,	width: 300
			,	maxWidth: 300
		});

		this.layertree = this.container.getComponent('layertree');
		this.availablelayertree = this.container.getComponent('availablelayertree');
					
		this.layertree.on('removeLayer', this.removeselectedLayer, this);
		this.layertree.on('checkchange', this.unchecklayers, this);
		this.layertree.on('nodeDeleted', this.nodeDeleted, this);

		this.availablelayertree.on('checkchange', this.findLayer, this);
		this.availablelayertree.getLoader().on('load',this.loadinitiallayers,this);
		
		items.push( this.container );
	}

	this.centerPanel = new GBIF.GeoSpatial.CenterPanel({
		region: 'center'	
	});
	items.push(this.centerPanel);
	
	this.mapComponent = this.centerPanel.mapComponent;
	
	if(Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs){
		this.tabmanager = this.centerPanel.tabmanager;
		GBIF.GeoSpatial.BUS.on('georsskmlClick', this.geoRsskmlClick, this);
	}
	
	this.proxyURL = Config.General.Home.url + "api/getcapabilities-proxy.php?url="
	
	GBIF.GeoSpatial.BUS.on('sendRequest',this.sendRequestForFeature, this);
	
	this.linkURL = new GBIF.GeoSpatial.CopyLink();
	this.linkURL.setText(this.txtText);
	
	this.linkURL.on('doupdateUrl', this.bookmarkLink, this);
	
	GBIF.GeoSpatial.BUS.on('exportImage',this.sendRequestToServer, this);
	
	GBIF.GeoSpatial.BUS.on('calculateHW',this.calculateHW, this);
	
	/*
	 * For export menu
	 */
	var exportmenu=[];
	
	if(Config.General.downloadFormats.Image){
		exportmenu.push(Config.General.ContextMenu.exportMenu.Image);
	}
/*	
	if(Config.General.downloadFormats.CSV){
		exportmenu.push(Config.General.ContextMenu.exportMenu.CSV);
	}
		
	if(Config.General.downloadFormats.GML2){
		exportmenu.push(Config.General.ContextMenu.exportMenu.GML2);
	}
		
	if(Config.General.downloadFormats.GML2GZIP){
		exportmenu.push(Config.General.ContextMenu.exportMenu.GML2GZIP);
	}
		
	if(Config.General.downloadFormats.GeoJSON){
		exportmenu.push(Config.General.ContextMenu.exportMenu.GeoJSON);
	}
		
	if(Config.General.downloadFormats.Shapefile){
		exportmenu.push(Config.General.ContextMenu.exportMenu.Shapefile);
	}
*/	

	var tbar = null;
	if (config.showMenu) {
		tbar = [{
					xtype: 'button'
				,	text:this.txtFile
				,	menu: [{
							text: this.txtExport
						,	iconCls:'icon-export'
						,	scope:this
						,	menu: {
									items:exportmenu
								,	scope:this
							}
					}]
			}, {
					xtype: 'button'
				,	text:this.txtView
				,	ref:'../viewmenu'
				,	scope:this
				,	menu: [{
							text: this.txtToolBar
						,	scope: this
						,	checked: true
						,	itemId:'addToolbar'
						,	checkHandler:this.addToolbarToMap
					}, '-' ,{
							text: this.txtOverviewMap
						,	checked: false
						,	scope: this
						,	itemId:'overviewButton'
						,	checkHandler: this.toggleoverviewmap
					}, {
							text: this.txtScaleLegend
						,	checked: true		
						,	scope: this
						,	itemId:'scaleLegendButton'
						,	checkHandler: this.togglescaleline
					}]
				}, {
						xtype: 'button'
					,	text: this.txtHelp
					,	menu: {
								items:Config.General.ToolbarMenu.HelpMenu
							}
					}
					, this.linkURL	
					, {
							xtype:'label'							
						,	html:'<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script><a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4c720a4c4586ed73"><img src="http://s7.addthis.com/static/btn/sm-share-en.gif" width="83" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4c720a4c4586ed73"></script>'
				}, '->', {
						xtype:'label'							
					,	html: 'Language: '
				}, {
						xtype: 'combo'	
					,	store: language
					,	mode: 'local'
					,	value: lang
					,	displayField: 'value'
					,	valueField: 'id'
					,	typeAhead: false
					,	fieldLabel:'Language'
					,	triggerAction: 'all'
					,	editable: false
					,	width: 76
					,	listeners: {
							select: function(f,r,i){
								var lang = r.data.id;
								window.location = "http://" + location.hostname + location.pathname + '?lang='+ lang;
							}	
						}		
				}]		
	}
	
	/*
	 * End of export menu.
	 */			
	Ext.apply(this, config, {
			region: 'center'
		,	border: false
		,	layout: 'border'
		,	defaults: {
				border: false
			}
		,	items: items
		,	tbar: tbar
	});
	
	GBIF.GeoSpatial.GeoSpatialPortal.superclass.constructor.call(this,config);

	Ext.get('loading-mask').fadeOut({remove:true});
	Ext.get('loading').remove();						

}

Ext.extend(GBIF.GeoSpatial.GeoSpatialPortal, Ext.Panel, {
	
		calculateHW: function(){
			return this.mapComponent.getSize();
		}
	
	,	pageQuery: function(q) {
			if(q.length > 1) {
				this.q = q.substring(1, q.length);
			} else {
				this.q = null;
			}
			this.keyValuePairs = new Array();
			
			if(q) {
				for(var i=0; i < this.q.split("&").length; i++) {
					this.keyValuePairs[i] = this.q.split("&")[i];
				}
			}
			this.getKeyValuePairs = function() { return this.keyValuePairs; }
			
			this.getParameters = function() {
				var a = new Array(this.getLength());
				for(var j=0; j < this.keyValuePairs.length; j++) {
					a[j] = this.keyValuePairs[j].split("=")[0];
				}
				return a;
			}

			this.getLength = function() {
				return this.keyValuePairs.length;
			}
		}
	
	,	getValue:function(s) {
			for(var j=0; j < this.keyValuePairs.length; j++) {
				if(this.keyValuePairs[j].split("=")[0] == s) {
					return this.keyValuePairs[j].split("=")[1];
				}
			}
			return false;
		}	
	
	,	queryString:function(key){
			this.pageQuery(window.location.search);
			return unescape(this.getValue(key));
		}
	
	,	displayItem: function(key){
			var a = this.queryString(key);
			if (a == 'false'){
				return false;
			} else {
				return a;
			}
		}
	
	,	addInitialLayer:function(layers){
			for (var i = 0; i < layers.length; i++) {
				var layerName = layers[i].name;
				var opacity = layers[i].opacity;
				var layernode = this.availablelayertree.getNodeById(layerName);
				if (layernode) {
					if (!layernode.getUI().isChecked()) {
						layernode.attributes.layer.opacity = opacity ;
						layernode.getUI().toggleCheck();
						layernode.attributes.checked = true;
						this.setOpacityForLayer(layerName,opacity );
					}
				} else {
					var node = this.availablelayertree.getNodeById("GBIF Occurrence");
					node.expand();
				}
			} 
		}	
	
	,	addInitialView:function(view){
			var addtbbtn = this.viewmenu.menu.getComponent('addToolbar');
			addtbbtn.setChecked(view[0].toolbar);
			var overviewbtn = this.viewmenu.menu.getComponent('overviewButton');
			overviewbtn.setChecked(view[0].overview);
			var scalelegendbtn = this.viewmenu.menu.getComponent('scaleLegendButton');
			scalelegendbtn.setChecked(view[0].scalelegend);	
		}		
		
	,	bookmarkLink:function(){
			var url = this.createBookmarkUrl();
			this.linkURL.updateUrl(url);
		}
	
	,	createBookmarkUrl:function(){
			var layers = [];
			var list = this.layertree.getChecked();
			Ext.each(list,function(item){
				if (item.text != 'World Map' && item.text != 'Feature Layer') {
					var item = {
							name: encodeURI(item.text)
						,	opacity: item.layer.opacity || 1
					}
					layers.push(item);	
				}
			}, this);
			
			var lc = layers.length;
			var z = this.mapComponent.map.zoom;
			var lat = this.mapComponent.map.center.lat;
			var lon = this.mapComponent.map.center.lon;
			
			var toolbar = this.viewmenu.menu.getComponent('addToolbar').checked;
			var overview = this.viewmenu.menu.getComponent('overviewButton').checked;
			var scalelegend = this.viewmenu.menu.getComponent('scaleLegendButton').checked;
			var view = [{
					toolbar: toolbar
				,	overview: overview
				,	scalelegend: scalelegend	
			}]
					
			var url = "http://" + location.hostname + location.pathname + "?lat=" + lat + "&lon=" + lon + "&lc=" + lc + "&z=" + z + "&view=" + Ext.encode(view) + "&layers=" + Ext.encode(layers);
			return url;
		}
	
	,	loadinitiallayers: function(){
			var url = Ext.urlDecode(location.search.substring(1));

			var layers = this.displayItem('layers');
			if(layers){
				var layers = Ext.decode(layers);
				this.addInitialLayer(layers);
			}
			
			var view = this.displayItem('view');
			if(view){
				var view = Ext.decode(view);
				this.addInitialView(view);
			}
			
			this.mapComponent.map.setCenter(new OpenLayers.LonLat(url.lon || 12 , url.lat || 7), url.z || 4);
			
			/*
			 * Removes mask after loading data.
			 */
			if(!Ext.isEmpty(Ext.get('loading'))){
				Ext.get('loading-mask').fadeOut({remove:true});
				Ext.get('loading').remove();	
				/*Ext.get('addthis').addListener('click',function(){
							var url = this.createBookmarkUrl();
							Ext.get('addthis').getAttribute('addthis:url').value = url;
							console.log("Ext.get('addthis')",Ext.get('addthis'),Ext.get('addthis').getAttribute('addthis:url') );
					},this);	*/
				}
		}
			
	,	setOpacityForLayer:function(layer,opacity){
			var list=this.layertree.getRootNode().childNodes;
			Ext.each(list, function(item){
				if (item.text == layer) {
					item.layer.opacity = opacity;
					item.layer.setOpacity(opacity);
				}
			}, this);
		}
	
	,	exportImage:function(format){
			var exportformat = '';
			switch(format) {
				case 'Composite Image':
					exportformat = 'image/png'
					break;
				case 'CSV':
					exportformat = 'csv'
					break;
				case 'GML2':
					exportformat = 'GML2'
					break;
				case 'GML2-GZIP':
					exportformat = 'GML2-GZIP'
					break;
				case 'GeoJSON':
					exportformat = 'json'
					break;	
				case 'Shapefile':
					exportformat = 'SHAPE-ZIP'
					break;				
			}

			var exportdata = [];
			var size = this.mapComponent.getSize();
			var height = size.height;
			var width = size.width;
			var layer='';
			Ext.each(this.mapComponent.map.layers,function(maplayer){
				if (maplayer.visibility) {
					if (maplayer.CLASS_NAME == "OpenLayers.Layer.WMS") {
						layer = {
								version:maplayer.params.VERSION
							,	request:maplayer.params.REQUEST
							,	layers:maplayer.params.LAYERS
							,	styles:maplayer.params.STYLES
							,	bbox: maplayer.map.getExtent().toBBOX()
							,	width: width
							,	height: height
							,	srs:maplayer.params.SRS
							,	opacity : maplayer.opacity || 1
							,	format : exportformat
							,	url : maplayer.params.URL||maplayer.url
							,	TRANSPARENT: "TRUE"
							,	FILTER: maplayer.params.FILTER
							,	CQL_FILTER: maplayer.params.CQL_FILTER
						}

						if (Ext.isDefined( maplayer.params.CQL_FILTER ) ) {
							layer.CQL_FILTER = maplayer.params.CQL_FILTER;
						}
						
						if (Ext.isDefined( maplayer.params.FILTER ) ) {
							layer.FILTER = maplayer.params.FILTER;
						}
						exportdata.push(layer);
					}
				}
			}, this);

			if (exportformat != 'image/png') {
				this.sendRequestToServer(layer,exportformat);
			} else {
				this.sendRequestToServer(exportdata,exportformat);
			}
		}
	
	,	sendRequestForFeature:function(layer,xy){
			if(Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs){
				var params = {
						request: "GetFeatureInfo"
					,	version: layer.params.VERSION   //'1.0.0'
					,	bbox: layer.map.getExtent().toBBOX()
					,	x: xy.x
					,	y: xy.y
					,	info_format:'application/vnd.ogc.gml'
					,	query_layers: layer.params.LAYERS
					,	srs: layer.params.SRS   //'EPSG:4326'
					,	layers: layer.params.LAYERS
					,	styles: ''
					,	width: layer.map.size.w
					,	height: layer.map.size.h
					,	format: 'image/png'
					,	filter: layer.params.FILTER
					,	cql_filter: layer.params.CQL_FILTER
				};

				if (layer.visibility) {
					Ext.Ajax.request({
						url: Config.General.Home.url + "api/getfeatureinfo-proxy.php?url=" + layer.url
						,	method: 'POST'
						,	timeout: 120000
						,	scope: this
						,	params: params
						,	success: function(responseObject){
								var data = Ext.decode(responseObject.responseText);
								this.checkforException(data, layer);
							}
						,	failure: function(){
								GBIF.GeoSpatial.Notice.msg("Exception", "Service Exception");
							}
					}, this);
				}

			}
		}

	,	checkforException: function(data,layer){
			var dataAvailable = (typeof data.FeatureCollection == 'undefined') ? false : true;
			if (dataAvailable) {
				var dataAvailable = (typeof data.FeatureCollection.featureMember == 'undefined') ? false : true;
				if (dataAvailable) {
							this.senddataasperlayer(data,layer);
				} else {
					GBIF.GeoSpatial.Notice.msg("Exception", "Data not available for " + layer.name);
				}
			} else {
				var dataAvailable = (typeof data.FeatureInfoResponse == 'undefined') ? false : true;
				if (dataAvailable) {
					this.senddataasperlayer(data, layer);
				}else {
					var dataAvailable = (typeof data.ServiceException == 'undefined') ? false : true;
					if (dataAvailable) {
						GBIF.GeoSpatial.Notice.msg("Exception", data.ServiceException);
					}else {
						GBIF.GeoSpatial.Notice.msg("Exception", "Data not available " + layer.name);
					}
				}	
			}	
		}
	
	,	senddataasperlayer:function(data,layer){
			var zoom = this.mapComponent.map.zoom;
			var name = layer.name;
			if(layer.params.LAYERS == 'geobon_tax_occurrence'){
				name ='GBIF Tax Occurrence';
			}
			var data = MappingLayers(name,zoom,data);
			this.loadinGrid(data,layer);
		}

	,	loadinGrid:function(data,layer){
			var zoom = this.mapComponent.map.zoom;
			Ext.each(this.tabmanager.items.items, function(item){
					if (item.title == layer.name) {
						if (zoom > 12) {
							item.getColumnModel().setConfig(layer.zoomcolumns);
						}else {
							item.getColumnModel().setConfig(layer.columns);
						}
						item.store.loadData(data);
						this.tabmanager.setActiveTab(item);
					}
			}, this);
		}
	
	,	sendRequestToServer: function(exportdata, exportformat){
			if (exportformat == 'image/png') {
				this.sendRequestForCompositeImage(exportdata);
				return;
			} else {				
				window.open(Config.General.Home.url + 'api/proxy.php?' + Ext.urlEncode(exportdata), '_blank');
			}
		}
		
	,	sendRequestForCompositeImage: function(exportdata){
			var size = this.mapComponent.getSize();
			var height = size.height;
			var width = size.width;
			window.open(Config.General.Home.url + 'api/composite.php?layers=' + Ext.encode(exportdata) + "&height=" + height + "&width=" + width, '_blank');
		}	
		
	,	geoRsskmlClick: function(data){
			if (Config.GBIF.GeoSpatial.TabManager.tabConfig.georssShow) {
				var georsskmlpanel = this.tabmanager.getComponent('georsskmldatapanel');
				this.tabmanager.setActiveTab( georsskmlpanel );
				georsskmlpanel.body.update( data );
			}
		}
		
	,	togglescaleline: function(btn){
			if(this.mapComponent.scaleline){
				if (btn.checked == true) {
					this.mapComponent.scaleline.div.style.zIndex = '1005';
					this.mapComponent.scaleline.activate();
				} else {
					this.mapComponent.scaleline.div.style.zIndex = '-1005';
					this.mapComponent.scaleline.deactivate();
				}	
			}
		}
	
	,	nodeDeleted:function(node){
			var list = this.availablelayertree.getChecked();
			Ext.each(list, function(item){
				if (item.text == node.text) {
					if (item.getUI().isChecked()) {
						this.availablelayertree.suspendEvents();
						item.getUI().toggleCheck();
						item.attributes.checked = false;
						this.availablelayertree.resumeEvents();
					}
				}
			}, this);
			this.deleteTab(node.text)
		}
	
	,	deleteTab:function(tabId){
			if (Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs) {
				Ext.each(this.tabmanager.items.items, function(item){
					if (item.itemId == tabId) {
						this.tabmanager.remove(item);
					}
				}, this);
			}
		}
	
	,	findLayer: function(node,checked){
			var presentlayer=false;
			Ext.each(this.mapComponent.map.layers,function(maplayer){
				if(maplayer.name == node.text ){
					presentlayer = true;
				}
			});
			
			if(checked ){
				if(!presentlayer){
					this.addLayer(node);			
				}else{
					var list=this.layertree.getRootNode().childNodes;
					Ext.each(list,function(item){
						if(item.text == node.text){
							if(!item.getUI().isChecked()){
								this.layertree.suspendEvents();
								item.getUI().toggleCheck();
								item.attributes.checked=true;
								item.layer.display(true);
								this.layertree.resumeEvents();
							}
						}
					 },this);	
					if (node.attributes.mType == 'georss' || node.attributes.mType == 'kml') {
								this.hideunhideGeoKmlTab(false, node);
					}else {
								this.hideunhideTabItem( false , node );
					}
				}
			} else {
				if (node.attributes.mType == 'georss' || node.attributes.mType == 'kml') {
					this.hideunhideGeoKmlTab(true, node);
				} else {
					this.hideunhideTabItem(true, node);
				}
				this.hideLayer(node);
			}	
		}

	,	unchecklayers: function(node, checked){
			if(!checked) {
				var list=this.availablelayertree.getChecked();
				Ext.each(list,function(item){
				 if(item.text == node.text){
						if (item.getUI().isChecked()) {
							this.availablelayertree.suspendEvents();					
							item.getUI().toggleCheck();
							item.attributes.checked=false;
							this.availablelayertree.resumeEvents();
						}	
					}
				},this);

				if (node.attributes.layer.CLASS_NAME == 'OpenLayers.Layer.GML' || node.attributes.layer.CLASS_NAME == 'GBIF.GeoSpatial.GeoRSS') {
					this.hideunhideGeoKmlTab(true, node);
					return;
				} else {
					this.hideunhideTabItem(true, node);
				}

			} else {
				if (node.layer.opacity == 0){
					node.layer.setOpacity(0.10);
					this.layertree.opacitySlider.setValue(10);
				}

				var layernode = this.availablelayertree.getNodeById(node.text);
				if (layernode) {
					if (!layernode.getUI().isChecked()) {
						this.availablelayertree.suspendEvents();
						layernode.getUI().toggleCheck();
						layernode.attributes.checked = true;
						this.availablelayertree.resumeEvents();
					}
				}	
					
				if (node.attributes.layer.CLASS_NAME == 'OpenLayers.Layer.GML' || node.attributes.layer.CLASS_NAME == 'GBIF.GeoSpatial.GeoRSS'){
					this.hideunhideGeoKmlTab(false ,node);			
					return;
				} else {
					this.hideunhideTabItem( false , node );	
				}
			}
		}
		
	,	hideunhideGeoKmlTab:function(hideunhide , node){
			if (Config.GBIF.GeoSpatial.TabManager.tabConfig.georssShow) {
				if(hideunhide){
					if(this.tabmanager.activeTab.title == 'GeoRss/Kml'){
						this.tabmanager.setActiveTab(0);	
					}
					Ext.each(this.tabmanager.items.items,function(item){
						item = (typeof item == 'undefined') ? false : item;
						if (item) {
							if (item.title == 'GeoRss/Kml') {
								this.tabmanager.hideTabStripItem(item);
							}
						}
					},this);

				} else {
					Ext.each(this.tabmanager.items.items,function(item){
						item = (typeof item == 'undefined') ? false : item;
						if (item) {
							if (item.title == 'GeoRss/Kml') {
								this.tabmanager.unhideTabStripItem(item);
							}
						}
					}, this);
				}
			}		
		}	
		
	,	hideunhideTabItem:function( hideunhide , node ){
			if (Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs) {
				if(hideunhide){
					if(this.tabmanager.activeTab.title == node.text){
						this.tabmanager.setActiveTab(0);	
					}
					Ext.each(this.tabmanager.items.items,function(item){
						item = (typeof item == 'undefined') ? false : item;
						if (item) {
							if (item.title == node.text) {
								this.tabmanager.hideTabStripItem(item);
							}
						}
					},this);
				} else {
					Ext.each(this.tabmanager.items.items,function(item){
						item = (typeof item == 'undefined') ? false : item;
						if (item) {
							if (item.title == node.text) {
								this.tabmanager.unhideTabStripItem(item);
							}
						}
					},this);
				}
			}	
		}	
	
	,	toggleoverviewmap: function(btn){
			if (this.mapComponent.overviewmap){
				if (btn.checked == true) {
					this.mapComponent.overviewmap.maximizeControl();
				} else {
					this.mapComponent.overviewmap.minimizeControl();
				}	
			}
		}

	,	removeselectedLayer: function( node ) {
			var text = node.text;
			var removelayer;
			Ext.each(this.mapComponent.map.layers,function(maplayer){
				if(maplayer.name == text){
					removelayer = maplayer;
				}
			});
			this.mapComponent.map.removeLayer(removelayer);
		}	
	
	,	addLayer: function(node){
			if(node.attributes.layer != ''){
				switch(node.attributes.mType) {
					case 'wms':
							this.addWMSLayerToMap(node);
							break;
					case 'georss':
							this.addGEORSSLayerToMap(node);
							break;
					case 'kml':
							this.addKMLLayerToMap(node);
							break;
					case 'gml':
							this.addGMLLayerToMap(node);
							break;	
					case 'wfs':
							this.addWFSLayerToMap(node);
							break;							
				}
			}

			if (Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs){
				if(node.attributes.layer.querable){
					var datagrid = new GBIF.GeoSpatial.DataGrid({
							columns: node.attributes.layer.columns || []
						,	fields: node.attributes.layer.fields	
						,	title: node.text
						,	itemId: node.text
					});
			
					GBIF.GeoSpatial.BUS.fireEvent('addTab', datagrid, this);
				}
			}
		}
	
	,	hideLayer:function(node){
			var checkedlayer;
			Ext.each(this.mapComponent.map.layers,function(maplayer){
				if(maplayer.name == node.text ){
					checkedlayer = maplayer;
				}
			});
			if(checkedlayer){
				checkedlayer.display(false);
				var list=this.layertree.getRootNode().childNodes;
				Ext.each(list,function(item) {
					if(item.text == node.text) {
						if(item.getUI().isChecked()){
							this.layertree.suspendEvents();
							item.getUI().toggleCheck();
							item.attributes.checked=false;
							this.layertree.resumeEvents();
						}
					}
				 }, this);
			}
		}
			
	,	addWMSLayerToMap:function(node){
			var data = node.attributes.layer;
			data.type = (typeof data.type == 'undefined') ? '' : data.type;

			var params = {
					layers: data.layers
				,	format: data.FORMAT
				,	filter: data.filter || ''
			}

			if (data.transparent == true) {
			}
				params.transparent = "TRUE";

			params.quality = 24;
			
			if (data.version != "") {
				params.version = data.version;
			}

			if (data.CQL_FILTER != '') {
				params.CQL_FILTER = data.CQL_FILTER;
			}

			var options = {
					querable: data.querable || ''
				,	columns: data.columns || ''
				,	zoomcolumns: data.zoomcolumns || data.columns  || ''
				,	fields: data.fields || ''
				,	buffer: 0
				,	downloadFormats : data.downloadFormats || {
							Image: true
						,	CSV: false
						,	GML2: false
						,	GML2GZIP: false	
						,	GeoJSON: false
						,	Shapefile: false
					}
			}
 
			var layer = new OpenLayers.Layer.WMS(
					node.text
				,	data.url
				,	params
				,	options
			);
			
			this.mapComponent.map.addLayer( layer );
		}	
		
	,	addGEORSSLayerToMap: function(node){
			var data = node.attributes.layer;
			var url = this.proxyURL + data.url;
			var yelp = new OpenLayers.Icon(Config.General.Home.url + "images/img/marker-gold.png", new OpenLayers.Size(10,15));
			var layer = new GBIF.GeoSpatial.GeoRSS(
					node.text
				, url
				, {	icon: yelp }
				,	Ext.apply(data)
			);

			layer.markerClick = function(evt){
				GBIF.GeoSpatial.BUS.fireEvent('georsskmlClick', this.data.popupContentHTML, this);
			}
			this.tabmanager = this.centerPanel.tabmanager;
			var presenttab=false;
			Ext.each(this.tabmanager.items.items,function(item){
				item = (typeof item == 'undefined') ? false : item;
				if (item) {
					if (item.title == 'GeoRss/Kml') {
						presenttab = true;
					}
				}
			}, this);

			if(!presenttab){
				var georsskmldatapanel = new GBIF.GeoSpatial.GeoRssKmlDataPanel(); 	
				GBIF.GeoSpatial.BUS.on('addTab', georsskmldatapanel, this);
				GBIF.GeoSpatial.BUS.on('georsskmlClick', this.geoRsskmlClick, this);
			}			
			this.mapComponent.map.addLayer(layer);
		}

	,	addKMLLayerToMap: function(node){
			var data = node.attributes.layer;
			var url = this.proxyURL + data.url;
			var layer = new OpenLayers.Layer.GML(
					node.text
				, url
				,	{
							format: OpenLayers.Format.KML
						,	formatOptions: {
									extractStyles: data.extractStyles
								,	extractAttributes: data.extractAttributes
								,	maxDepth: data.maxDepth
							}
					}
			);
			
			var selectControl = new GBIF.GeoSpatial.SelectFeature(layer);
			this.mapComponent.map.addControl(selectControl);
			selectControl.activate();
			selectControl.onSelect = function(feature){
				GBIF.GeoSpatial.BUS.fireEvent('georsskmlClick',feature.data.description,this);
			}
			
			this.tabmanager = this.centerPanel.tabmanager;
			var presenttab=false;	
			Ext.each(this.tabmanager.items.items,function(item){
				item = (typeof item == 'undefined') ? false : item;
				if (item) {
					if (item.title == 'GeoRss/Kml') {
						presenttab = true;
					}
				}
			},this);
			
			if(!presenttab){
				var georsskmldatapanel = new GBIF.GeoSpatial.GeoRssKmlDataPanel(); 	
				GBIF.GeoSpatial.BUS.fireEvent('addTab', georsskmldatapanel, this);
				Config.GBIF.GeoSpatial.TabManager.tabConfig.georssShow = true;
				GBIF.GeoSpatial.BUS.on('georsskmlClick', this.geoRsskmlClick, this);
			}		
			this.mapComponent.map.addLayer(layer);	
		}

	,	addGMLLayerToMap:function(node){
			var data = node.attributes.layer;
			var url = this.proxyURL + data.url;
			var layer = new OpenLayers.Layer.GML(
					node.text
				, url
			);
			this.mapComponent.map.addLayer(layer);		
		}

	,	addWFSLayerToMap:function( data ){
//			var data = node.attributes.layer;
			var strategies = [ new OpenLayers.Strategy.BBOX() ];
			if (data.editable) {
				strategies.push( new OpenLayers.Strategy.Save() );
			}
			
			var wfs = new OpenLayers.Layer.Vector(
					data.text
				, {
						strategies: strategies
					,	querable: data.querable
					,	protocol: new OpenLayers.Protocol.WFS({
								version: "1.1.0"
							,	url: data.url
//							,	request: 'GetFeature'	
							,	featureType: data.featureType
							,	featureNS: data.featureNS
							,	geometryName: data.geometryName
							,	schema: data.schema
						})
			});
				
			this.mapComponent.map.addLayer(wfs);
			return( wfs );
		}
		
	,	addToolbarToMap:function(btn,checked){
			if (checked) {
				this.centerPanel.controlPanel();
			} else {
				Ext.each(this.mapComponent.map.controls,function(control){
					control = (typeof control == 'undefined') ? false : control;
					if (control) {
						if (control.CLASS_NAME == "OpenLayers.Control.Panel") {
							control.destroy();
						}
					}	
				}, this);
			}
		}	
});